package com.wuxiaolong.wechat.util;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Map;

/**
 * Description:
 *
 * @author Leo
 * @date 2020-02-12
 */
@Slf4j
public class WxUtil {



    /**
     * 校验微信签名
     * 1）将token、timestamp、nonce三个参数进行字典序排序
     * 2）将三个参数字符串拼接成一个字符串进行sha1加密
     * 3）开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
     * @return
     */
    public static boolean checkSign(String token, String timestamp, String nonce,String signature){

        String[] params = new String[]{token, timestamp, nonce};
        Arrays.sort(params);

        String src = params[0] + params[1] + params[2];
        String tempSign = sha1(src);

        log.info("signature:" + signature);
        log.info("tempSign :" + tempSign);

        return signature.equals(tempSign);
    }

    /**
     * sha1签名
     * @return
     */
    public static String sha1(String src){

        // 需要用到的对应的字符串
        char[] chars = new char[]{'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};

        //接收结果对象
        StringBuilder sb = new StringBuilder();

        try {
            // 1.获取一个加密对象
            MessageDigest md = MessageDigest.getInstance("sha1");

            // 2.加密
            byte[] digest = md.digest(src.getBytes());

            // 3.处理每个字节
            for(byte b : digest){
                // 处理高四位
                int b1 = b>>4;
                int b2 = b1&15;
                sb.append(chars[b2]);

                // 处理第四位
                int b3 = b&15;
                sb.append(chars[b3]);
            }

        } catch (NoSuchAlgorithmException e) {
            log.error("签名失败", e);
        }

        return sb.toString();
    }

}
